package com.xhh.greynewsapp.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.xhh.greynewsapp.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class NewsInfoActivity extends AppCompatActivity {

    private static final String TAG = "NewsInfoActivity";

    @BindView(R.id.news_web_view)
    WebView webView;

    @BindView(R.id.btn_back)
    Button btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_info);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        String url = intent.getStringExtra("URL");
        Log.e(TAG, url);

        showInfo(url);

    }

    private void showInfo(String url) {
        WebSettings settings = webView.getSettings();
        //允许js
        settings.setJavaScriptEnabled(true);

        //加载网页
        webView.loadUrl(url);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(webView.canGoBack()){
                    webView.goBack();
                    finish();
                }
            }
        });

        //捕获网页访问的网址
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                Uri uri=Uri.parse(url);
                if(uri.getScheme().equals("js")){
                    if(uri.getAuthority().equals("webView")){
                        String name = uri.getQueryParameter("name");
                        String age = uri.getQueryParameter("age");
                        Toast.makeText(NewsInfoActivity.this,"安卓捕获了网页的访问网址"+name+" "+age,Toast.LENGTH_SHORT).show();
                        return true;
                    }
                }else{
                    webView.loadUrl(url);
                }
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()){
            webView.goBack();
            finish();
            return;
        }
        super.onBackPressed();
    }
}
